package com.usian.app.filter;

import com.usian.admin.jwt.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Component
@Log4j2
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1、获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2、判断当前是否是登录或注册
        String [] url ={"/in","/register","/login"};
        for (String s : url) {
            if (request.getURI().getPath().contains(s)){
                return chain.filter(exchange);
            }
        }
        //3、获取请求头中的jwt信息
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");
        //判断是否存在token(是否登录)
        if (StringUtils.isBlank(token)){
           String json = "{\"errorMessage\":\"not login\"}";
           return response.writeWith(Flux.just(response.bufferFactory().wrap(json.getBytes())));
        }
        //5、解析令牌,判断令牌是否有效
        Claims claims = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claims);
        if (i==0||i==-1){
            //5.1 合法，则向header中重新设置userId
            Integer id = (Integer) claims.get("id");
            log.info("find userid:{} from uri:{}",id,request.getURI());
            //重新设置token到header中
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", id + "");
            }).build();
            exchange.mutate().request(serverHttpRequest).build();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
